package br.com.tcc.systemdx.persistence.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import br.com.tcc.systemdx.commons.persistence.CriteriaTransformer;
import br.com.tcc.systemdx.domain.BaseEntity;

public abstract class AbstractEntityHibernateDAOImpl<T extends BaseEntity> extends
		AbstractHibernateDAOImpl<T, Long> {
	
	public void deletar(Long id) throws Exception {
		T t = findById(id);
		
		if (t != null) {
			this.makeTransient(t);
		}
	}
	
	public void deletar(T instance) throws Exception {
		if (instance != null && instance.getId() != null)
			this.makeTransient(instance);
			
	}
	
	public T salvar(T instance) throws Exception {
		if (instance.getId() != null) {
			disconnect(instance);
			instance = this.updateCopy(instance);
		} else {
			instance = makePersistent(instance);
		}
		_getSession().flush();
		return instance;
	}
	
	public List<T> salvar(List<T> instances) throws Exception {
		List<T> salvos = new ArrayList<T>(instances.size());
		for (T t : instances) {
			salvos.add(salvar(t));
		}
		return salvos;
	}
	
	public T findById(Long id) {
		return super.findById(id);
	}
	
	public T findById(Long id, CriteriaTransformer criteriaTransformer) {
		if (criteriaTransformer != null)
			return (T) criteriaTransformer.transformCriteria(createCriteria(Restrictions.eq("id", id))).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).uniqueResult();
		else
			return findById(id);
	}
}
